package com.zyf.chapter02.creation.singleton;

import java.util.concurrent.atomic.AtomicLong;

/**
 * id 生成器 集群唯一
 * @author yifeng
 */
public class IdGeneratorClusterUnique {
    private AtomicLong id = new AtomicLong(0);
    private static IdGeneratorClusterUnique instance;
    private static SharedObjectStorage storage = new FileSharedObjectStorage(/*入参省略，比如文件地址*/);
    private static DistributeLock lock = new DistributeLock();

    private IdGeneratorClusterUnique() {}

    public synchronized static IdGeneratorClusterUnique getInstance() {
        // 获取 加锁
        if (instance == null) {
            lock.lock();
            instance = storage.load(IdGeneratorClusterUnique.class);
        }
        return instance;
    }

    public synchronized void freeInstance() {
        storage.save(this, IdGeneratorClusterUnique.class);
        instance = null; // 释放对象
        lock.unlock();
    }

    public long getId() {
        return id.incrementAndGet();
    }

//------------------------依赖项-------------------------------
    private static interface SharedObjectStorage {
        void save(IdGeneratorClusterUnique idGeneratorClusterUnique, Class<IdGeneratorClusterUnique> idGeneratorClusterUniqueClass);

        IdGeneratorClusterUnique load(Class<IdGeneratorClusterUnique> idGeneratorClusterUniqueClass);
    }

    private static class FileSharedObjectStorage implements SharedObjectStorage {
        @Override
        public void save(IdGeneratorClusterUnique idGeneratorClusterUnique, Class<IdGeneratorClusterUnique> idGeneratorClusterUniqueClass) {

        }

        @Override
        public IdGeneratorClusterUnique load(Class<IdGeneratorClusterUnique> idGeneratorClusterUniqueClass) {
            return null;
        }
    }

    private static class DistributeLock {
        public void unlock() {

        }

        public void lock() {
        }
    }
}
